/**
 * 
 */
package bpel.instructions;

import java.rmi.RemoteException;
import java.util.LinkedList;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

import bpel.BPELProcess;

/**
 * @author Maurice & Topia
 * 
 */
public class BPELInvoke extends BPELInstruction {

	private String name;
	private String partnerLink;
	private String portType;
	private String operation;
	private String inputVariable;
	private String outputVariable;

	public BPELInvoke(String name, String partnerLink, String portType, String operation, String inputVariable, String outputVariable) {
		super();
		this.name = name;
		this.partnerLink = partnerLink;
		this.portType = portType;
		this.operation = operation;
		this.inputVariable = inputVariable;
		this.outputVariable = outputVariable;
	}

	@Override
	public String toString() {
		return "invoke : " + outputVariable + " " + name + "(" + inputVariable + ")" + " with (partnerLink=" + partnerLink + ", portType=" + portType + ", operation=" + operation + ")";
	}

	@Override
	public String execute(BPELProcess process) {

		
		System.out.println("TODO complete execute invoke function (get the parameters)");
		
		String result = null;

		try {
			Service service = new Service();
			Call call = (Call) service.createCall();
			
			call.setTargetEndpointAddress(process.getServiceURL(portType));
			
			call.setPortTypeName(new QName(portType));
			call.setOperation(operation);

			LinkedList<Object> parameters = new LinkedList<Object>();
			parameters.add(process.getVariable(inputVariable).getXMLDescription());
			
			process.getVariable(outputVariable).parse((String)call.invoke(parameters.toArray()));

		} catch (ServiceException e) {
			System.err.println("Invoke " + name + " failed");
			e.printStackTrace();
		} catch (AxisFault e) {
			System.err.println("Invoke " + name + " failed");
			e.printStackTrace();
		} catch (RemoteException e) {
			System.err.println("Invoke " + name + " failed");
			e.printStackTrace();
		}
		
		return result;
	}
}
